package com.hsgene.common.util.web.access;

import com.hsgene.common.util.http.HttpRequestUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * HttpRequest调试过滤器
 *
 * @author wangbing
 * @version 1.0, 2018/7/19
 */
public class HttpDebugFilter extends OncePerRequestFilter {

    private final static Logger LOG = LogManager.getLogger(HttpDebugFilter.class);

    /**
     * 调试HttpRequest的过滤器, 用于输出每次请求的相关信息, 方便在开发环境下进行调试.
     * 调试包含的信息: URI, Parameters, Headers, Sessions
     */
    private boolean logbackHttpDebug;

    @Override
    protected void initFilterBean() throws ServletException {
        super.initFilterBean();
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
                                    FilterChain filterChain) throws ServletException, IOException {

        if (logbackHttpDebug) {
            LOG.info(HttpRequestUtils.getRealRemoteAddr(request) + " " + request.getMethod() + " " + request.getRequestURI());
            LOG.info("Parameters: " + HttpRequestUtils.getParameters2Json(request));
            LOG.info("Headers: " + HttpRequestUtils.getHeaders2Json(request));
            LOG.info("Sessions: " + HttpRequestUtils.getSessionAttributes2Json(request));
        }
        filterChain.doFilter(request, response);
    }

    public boolean isLogbackHttpDebug() {
        return logbackHttpDebug;
    }

    public void setLogbackHttpDebug(boolean logbackHttpDebug) {
        this.logbackHttpDebug = logbackHttpDebug;
    }
}
